<?php

// @formatter:off
/**
 * @file login.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: login.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/services/users/login.php $
 */
// @formatter:on

class WCServiceUsersLogin extends WCService {
	//
	// Protected properties.
	protected $_password = false;
	protected $_rememberMe = false;
	protected $_username = false;
	//
	// Magic methods.
	public function __construct() {
		$this->_requiredParams["params"][] = "username";
		$this->_requiredParams["params"][] = "password";

		$this->_requiredPermissions["to"][] = WC_PERM_USER_LOGIN;
	}
	//
	// Public methods.
	public function load() {
		$out = false;

		if(parent::load()) {
			$this->_username = strtolower($this->username);
			$this->_password = $this->password;
			if(isset($this->keepme)) {
				$this->_rememberMe = ($this->keepme == "Y");
			}
			$out = true;
		}

		return $out;
	}
	//
	// Protected methods.
	protected function runPOST() {
		global $wcSession;

		if(!$wcSession->isLogged()) {
			$user = new WCUser();

			if($user->loadByAuth($this->_username, WCUser::EncryptPasswordString($this->_password))) {
				if($user->webAccess()) {
					setcookie(WC_COOKIE_KEEPME_USER, "", 1);
					setcookie(WC_COOKIE_KEEPME_HASH, "", 1);
					setcookie(WC_COOKIE_KEEPME_NAME, "", 1);

					if($wcSession->login($user->id)) {
						if($this->_rememberMe) {
							$wcSession->setRememberMe();
						}

						$this->_count++;
					} else {
						$this->setError(WC_HTTPERROR_INTERNAL_SERVER_ERROR, "Username and password are correct, but session could not be started");
					}
				} else {
					$this->setError(WC_HTTPERROR_UNAUTHORIZED, "User has no web access");
				}
			} else {
				$this->setError(WC_HTTPERROR_BAD_REQUEST, "Username or password incorrect");
			}
		} else {
			$this->setError(WC_HTTPERROR_BAD_REQUEST, "Session already started");
		}
	}
}
